<script setup lang="ts">
import { useSystemStore } from '~/stores/system'

interface Field {
  label: string
  prop: string
}

interface IProps {
  columns: Field[]
}

const formRef = ref()

const { columns } = defineProps<IProps>()

const state = reactive<Record<string, any>>({})

const syStore = useSystemStore()

const cols = computed(() => {
  const exclude = syStore.excludeKeys
  return columns.filter((k) => !exclude.includes(k.prop))
})

watch(() => cols.value, (cols) => {
  cols.forEach(col => {
    state[col.prop] = ''
  })
})

const emit = defineEmits(['onQuery', 'onCreate'])

const onQuery = (action: string) => {
  if (action === 'RESET') {
    emit('onQuery', {})
    formRef.value.resetFields()
  } else {
    emit('onQuery', toRaw(state))
  }
}

const onCreate = () => {
  emit('onCreate', {})
}

const offset = computed(() => {
  const columnsPerRow = 4
  const totalCols = cols.value.length
  const remainder = totalCols % columnsPerRow
  return (24 / columnsPerRow) * (columnsPerRow - remainder - 1)
})

const labelWidth = computed(() => {
  const maxLabelLength = Math.max(...cols.value.map(col => col.label.length))
  return maxLabelLength * 13
})

</script>

<template>
  <div class="search-form overflow-hidden">
    <el-form :label-width="labelWidth" ref="formRef" :model="state" @submit.native.prevent>
      <el-row :gutter="16">
        <template v-for="col in cols" :key="col.prop">
          <el-col :span="6">
            <el-form-item :label="col.label" :prop="col.prop">
              <el-input @keydown="onQuery('SEARCH')" v-model="state[col.prop]" :placeholder="$t('enter_input')" />
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="6" :offset="offset">
          <div class="flex items-center justify-end">
            <Button icon="search" @click="onQuery('SEARCH')">
              {{ $t('search') }}
            </Button>
            <Button icon="reset" class="ml-2" @click="onQuery('RESET')">
              {{ $t('reset') }}
            </Button>
            <Button icon="plus" class="ml-2" @click="onCreate()">
              {{ $t('add_row') }}
            </Button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.search-form {
  margin-bottom: 16px;
}
.mr-4px {
  margin-right: 4px;
}
</style>
